# ***********************************************
# * Automatic Script - Run only with Tournament *
# * Authors: André Bannwart Perina              *
# *          Antonio Canabrava Fraideinberze    *
# *          Willian Felipe Lopes da Silva      *
# ***********************************************

if [ $# -ne 14 ]; then
    echo "Usage: $0 loopTimes portNumber deltaSize numIters startIndex numProc filesPrefix outputFile tournamentSize percentage crossOver mutation beta noGenerate"
	echo " This script will ignore crossOver and Mutation parameters"
	echo " Use noGenerate != 0 to not generate new files"
    exit
fi

echo "Creating all folders..."
mkdir deltaFiles
mkdir fitnessFiles
mkdir stats

echo "Compiling all programs..."
make bin/generate
make bin/main
make bin/gapFillerBadKiller
make bin/histogramiser
make bin/tournament
make bin/fit

if [ ${14} -eq 0 ]; then
	echo "1. Generating individuals..."
	./bin/generate $3 $4 $5
else
	echo "1. Using already generated files..."
fi

echo "Running without crossover and mutation..."
c=$5
while (( $c < $1 ))
do
    echo "2. Simulating robots..."
    ./robot_par.sh $6 $4

    echo "3. Running gapFillerBadKiller..."
    ./bin/gapFillerBadKiller $4 $7 $3 0

    echo "4. Running histogramiser..."
    ./bin/histogramiser $7 $8 $4

    echo "5. Plotting the histogram..."
    cd tournament
    gnuplot -e "load 'hist.p'"
    cd ..

    echo "6-8. Renaming the histogram..."
    mv tournament/histogram.png tournament/generation$c.png
    mv tournament/data.dat tournament/generation$c.dat

    echo "9. Running the tournament..."
    ./bin/tournament $7 $8 $4 $9

    echo "10-11. Plotting tournament result..."
    cd tournament
    gnuplot -e "load 'hist.p'"
    cd ..

    echo "12-13. Renaming the histogram..."
    cp tournament/histogram.png tournament/t_generation$c.png
    cp tournament/data.dat tournament/t_generation$c.dat

    echo "14. Creating folder for deltaFiles and copying files..."
    mkdir deltaFiles/generation$c
    cp deltaFiles/file_* deltaFiles/generation$c

    echo "15. Moving files for fitnessFiles..."
    mkdir fitnessFiles/generation$c
    mv fitnessFiles/file_* fitnessFiles/generation$c

    echo "16. Calculating stats for generation$c..."
    python3 src/stats.py $4 fitnessFiles/generation$c/file_ stats/generation$c ${13}

    echo "17. Running fit..."
    ./bin/fit $3 $4 ${10} 0 0

    echo "18. Running again from step 2."
    c=$((c+1))
done

echo "Cleaning temporary files..."
rm tournament/data.dat
rm tournament/histogram.png